//
//  ImageMagerViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/10.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "ImageMagerViewController.h"

#import "ImgManOneView.h"
#import "ImgManTwoView.h"
@interface ImageMagerViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>
{
    NSMutableArray *array;
    UIImagePickerController *imagepc;
    ImgManOneView *oneView;
    ImgManTwoView *twoView;
    UIPageControl *pagectl;
    NSInteger page;//当前页码
    UILabel *lab;//页数
}

@property (nonatomic,copy) NSString *imgUrl;//图片上传路径
@property (nonatomic,copy) NSString *imgUrl2;//

@property (nonatomic,copy) NSString *state;//标识符

@property (nonatomic,strong)NSDictionary *dic;

@property (nonatomic,strong)NSMutableArray *images;//图片数组

@property (nonatomic,strong)NSMutableArray *arrImageUrl;//

@property (nonatomic,strong)UIScrollView *sclViews;

@end

@implementation ImageMagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setBGColor];
    array = [NSMutableArray array];
    _images = [NSMutableArray array];
    _arrImageUrl = [NSMutableArray array];
    [self loadNav];
//    [self showNav:@""];
    [self loadData];
    [self loadUI];
}

- (void)loadNav{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    
    UILabel *labTit = [[UILabel alloc] init];
    labTit.text = @"店铺资料";
    labTit.textColor = [UIColor blackColor];
    labTit.font = [UIFont systemFontOfSize:18.0];
    [view addSubview:labTit];
    [labTit makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(view.centerX);
        make.top.equalTo(34);
    }];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    //返回按钮
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateHighlighted];
    [btn addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [btn makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(labTit.centerY);
        make.left.equalTo(5);
        make.width.equalTo(30);
        make.height.equalTo(30);
    }];
    
    //按钮
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    btn2.tag = 1;
    [btn2 setTitle:@"保存" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [btn2 addTarget:self action:@selector(clickRight) forControlEvents:UIControlEventTouchUpInside];
    btn2.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [view addSubview:btn2];
    [btn2 makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(labTit.centerY);
        make.right.equalTo(-5);
        make.width.equalTo(40);
        make.height.equalTo(30);
    }];
    
}
// 返回
- (void)clickBack{
    [self.navigationController popViewControllerAnimated:YES];
}
//保存
- (void)clickRight{
    if (_images.count <=0) {
        [LICGToast showWithText:@"请添加店铺广告图"];
        return;
    }else if (_imgUrl2.length <=0){
        [LICGToast showWithText:@"请添加店铺列表图"];
        return;
    }
    
    NSString *strimg = [_arrImageUrl componentsJoinedByString:@"|"];
    NSString *str = [NSString stringWithFormat:@"%@890d69e502d1d37a9e84335ccefece57",[user objectForKey:@"token2"]];
    NSString *token = [LCMD5Tool md5:str];
    
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:strimg forKey:@"figurepic"];
    [parmas setObject:_imgUrl2 forKey:@"listpic"];
    [parmas setObject:_merid forKey:@"id"];
    [parmas setObject:token forKey:@"verifiToken"];
    NSLog(@"parmas:%@",parmas);
    NSString *url = [NSString stringWithFormat:@"%@/App/Forbusiness/management",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"保存res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            [self.navigationController popViewControllerAnimated:YES];
        }
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
}

- (void)loadUI{
    UIScrollView *sclView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
    sclView.contentSize = CGSizeMake(ScreenWidth, 600);
    [self.view addSubview:sclView];
    //广告图
    oneView = [[[NSBundle mainBundle] loadNibNamed:@"ImgManOneView" owner:nil options:nil] lastObject];
    oneView.frame = CGRectMake(0, 0, ScreenWidth, 350);
    [sclView addSubview:oneView];
    
    //添加图片
    [oneView.btnAdd addTarget:self action:@selector(clickAdd) forControlEvents:UIControlEventTouchUpInside];
    
    _sclViews = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 200)];
    if (_arrImageUrl.count>0) {
        _sclViews.hidden = NO;
        
    }else{
        _sclViews.hidden = YES;
    }
    _sclViews.delegate = self;
    _sclViews.bounces = NO;
    //分页
    _sclViews.pagingEnabled = YES;
    [oneView.view1 addSubview:_sclViews];
    
    //店铺列表
    twoView = [[[NSBundle mainBundle] loadNibNamed:@"ImgManTwoView" owner:nil options:nil] lastObject];
    twoView.frame = CGRectMake(0, oneView.frame.origin.y+oneView.frame.size.height, ScreenWidth, 140);
    [sclView addSubview:twoView];
    
    twoView.view2.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(click2)];
    [twoView.view2 addGestureRecognizer:tap2];
    
    if ([_merchanttype integerValue] == 1 || [_merchanttype integerValue] == 2) {
        twoView.hidden = YES;
    }else{
        twoView.hidden = NO;
    }
    
}
//添加图片
- (void)clickAdd{
    _state = @"1";
    if (_images.count >= 6) {
        [LICGToast showWithText:@"最多上传6张图片"];
        return;
    }
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
}

//
- (void)click2{
    _state = @"2";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPicture];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"从相册中获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pickerPictureFromAlbum];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:YES completion:nil];
}

//拍照获取
- (void)pickerPicture{
    if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear]) {
        NSLog(@"用前置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagepc.delegate = self;
        imagepc.allowsEditing = YES;
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceRear;
        
    }else if ([UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]){
        NSLog(@"用后置摄像头");
        imagepc = [[UIImagePickerController alloc] init];
        imagepc.cameraDevice = UIImagePickerControllerCameraDeviceFront;
    }else{
        UIAlertController *a = [UIAlertController alertControllerWithTitle:@"调用失败" message:@"请从手机相册中选择" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:a animated:YES completion:nil];
    }
    
    [self presentViewController:imagepc animated:YES completion:nil];
}

//从手机的图片获取
- (void)pickerPictureFromAlbum{
    UIImagePickerController *imgpicker = [[UIImagePickerController alloc] init];
    imgpicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imgpicker.allowsEditing = YES;
    imgpicker.delegate = self;
    [self presentViewController:imgpicker animated:YES completion:nil];
    
}
#pragma -mark UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    if ([_state isEqualToString:@"1"]) {
        _sclViews.hidden = NO;
        //oneView.hidden = YES;
        
    }else{
        twoView.images.image = img;
        
    }
    
    [self loadImage:img];
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//图片上传
- (void)loadImage:(UIImage *)image{
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:@"pic.png" forKey:@"pic"];
    [parmas setObject:@"name" forKey:@"name"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/upload",urlHead];
    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        NSData *data = UIImageJPEGRepresentation(image, 0.5);
        [formData appendPartWithFileData:data name:@"pic" fileName:fileName mimeType:@"image/png"];
        [formData appendPartWithFileData:data name:@"name" fileName:fileName mimeType:@"image/png"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *op = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
        NSLog(@"dic:%@",op);
        NSString *error = [NSString stringWithFormat:@"%li",[[op objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            if ([_state isEqualToString:@"1"]) {
                _imgUrl = [op objectForKey:@"result"];
                [_arrImageUrl addObject:_imgUrl];
                NSString *imgs = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],_imgUrl];
                [_images addObject:imgs];
                
                _sclViews.hidden = NO;
                _sclViews.contentSize = CGSizeMake(ScreenWidth*_images.count, 200);
                
            }else{
                _imgUrl2 = [op objectForKey:@"result"];
            }
            
        }
        //轮播
        for (NSInteger i = 0; i<_images.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*ScreenWidth, 0, ScreenWidth , 200)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:_images[i]] placeholderImage:nil];
            
            [_sclViews addSubview:imageView];
            
            UIButton *btnDel = [UIButton buttonWithType:UIButtonTypeCustom];
            btnDel.frame = CGRectMake(ScreenWidth-40, 10+40, 30, 30);
            [btnDel setImage:[UIImage imageNamed:@"x-拷贝"] forState:UIControlStateNormal];
            btnDel.backgroundColor = [UIColor whiteColor];
            btnDel.layer.cornerRadius = 10.0;
            [btnDel addTarget:self action:@selector(clicks) forControlEvents:UIControlEventTouchUpInside];
            [oneView addSubview:btnDel];
            
        }
        
        lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-50, 150+40, 30, 30)];
        lab.text = [NSString stringWithFormat:@"%li/%li",page+1,_images.count];
        lab.textAlignment = NSTextAlignmentCenter;
        lab.backgroundColor = [UIColor grayColor];
        lab.textColor = [UIColor redColor];
        lab.layer.masksToBounds = YES;
        lab.layer.cornerRadius = 15.0;
        [oneView addSubview:lab];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}

#pragma -mark UIScrollViewDelegate
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    page = (int)(scrollView.contentOffset.x/scrollView.bounds.size.width + 0.5);
    lab.text = [NSString stringWithFormat:@"%li/%li",page+1,_images.count];
    pagectl.currentPage = page;
}
//删除
- (void)clicks{
    NSLog(@"page:%li",(long)page);
    
    NSString *files = _arrImageUrl[page];
    NSLog(@"file:%@",files);
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:files forKey:@"files"];
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/delfile",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"删除图片res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        if ([error integerValue] == 200) {
            [_images removeObjectAtIndex:page];
            [_arrImageUrl removeObjectAtIndex:page];
            _sclViews.contentSize = CGSizeMake(ScreenWidth*_images.count, 200);
            lab.text = [NSString stringWithFormat:@"%li/%li",page+1,_images.count];
        }
        
        [LICGToast showWithText:[responseObject objectForKey:@"mssage"]];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}


//图片管理
- (void)loadData{
    [SVProgressHUD show];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_merid forKey:@"merchantid"];
    NSString *url = [NSString stringWithFormat:@"%@/App/Forbusiness/markepic",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"图片管理res:%@",responseObject);
        _dic = [responseObject objectForKey:@"result"];
        NSString *str = [_dic objectForKey:@"figurepic"];
        if (str.length > 0) {
            
            NSString *figur = [_dic objectForKey:@"figurepic"];
            NSArray *arr = [figur componentsSeparatedByString:@"|"];
            _arrImageUrl = [arr mutableCopy];
            for (NSString *aaa in arr) {
                NSString *url1 = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],aaa];
                [_images addObject:url1];
            }
            _sclViews.contentSize = CGSizeMake(ScreenWidth*_arrImageUrl.count, 200);
            
            //轮播
            for (NSInteger i = 0; i<_images.count; i++) {
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(i*ScreenWidth, 0, ScreenWidth , 200)];
                [imageView sd_setImageWithURL:[NSURL URLWithString:_images[i]] placeholderImage:nil];
                
                [_sclViews addSubview:imageView];
                
                UIButton *btnDel = [UIButton buttonWithType:UIButtonTypeCustom];
                btnDel.frame = CGRectMake(ScreenWidth-40, 10+40, 30, 30);
                [btnDel setImage:[UIImage imageNamed:@"x-拷贝"] forState:UIControlStateNormal];
                btnDel.backgroundColor = [UIColor whiteColor];
                btnDel.layer.cornerRadius = 10.0;
                [btnDel addTarget:self action:@selector(clicks) forControlEvents:UIControlEventTouchUpInside];
                [oneView addSubview:btnDel];
                
            }
            
            lab = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth-50, 150+40, 30, 30)];
            lab.text = [NSString stringWithFormat:@"%li/%li",page+1,_images.count];
            lab.textAlignment = NSTextAlignmentCenter;
            lab.backgroundColor = [UIColor grayColor];
            lab.textColor = [UIColor redColor];
            lab.layer.masksToBounds = YES;
            lab.layer.cornerRadius = 15.0;
            [oneView addSubview:lab];
            
            _sclViews.hidden = NO;
        }else{
            _sclViews.hidden = YES;
        }
        
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[_dic objectForKey:@"listpic"]];
        _imgUrl2 = [_dic objectForKey:@"listpic"];
        [twoView.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@""]];
        
        [SVProgressHUD dismiss];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [SVProgressHUD dismiss];
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
